package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.User;
import com.jt.service.DubboUserService;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by FanJia on 2020/11/16 17:00
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Reference(check = false)
    private DubboUserService dubboUserService;
    @Autowired
    private JedisCluster jedisCluster;

    @RequestMapping("/{moduleName}")
    public String module(@PathVariable String moduleName){
        return moduleName;
    }

    /**
     * 完成用户的注册操作
     * url地址: http://www.jt.com/user/doRegister
     *          Request Method: POST
     * 请求参数:
     *          password: admin123
     *          username: admin123123123
     *          phone: 13111112225
     * 返回值类型:
     *          SysResult对象
     */
    @RequestMapping("/doRegister")
    @ResponseBody
    public SysResult saveUser(User user){

        //利用dubbo进行RPC调用
        dubboUserService.saveUser(user);
        return SysResult.success();
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public SysResult doLogin(User user, HttpServletResponse response){
        String uuid = dubboUserService.doLogin(user);
        if(StringUtils.isEmpty(uuid)){
            return SysResult.fail();
        }
        //将uuid保存到Cookie中
        Cookie cookie = new Cookie("JT_TICKET",uuid);
        cookie.setMaxAge(30*24*60*60);  //让cookie 30天有效
        cookie.setPath("/");            //cookie在哪个url路径生效
        cookie.setDomain("jt.com");     //设定cookie共享
        response.addCookie(cookie);

        return SysResult.success();
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        //1.获取Cookie中的JT_TICKET值
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length>0){
            for (Cookie cookie : cookies){
                if(cookie.getName().equals("JT_TICKET")){
                    String ticket = cookie.getValue();
                    //redis删除ticket信息
                    jedisCluster.del(ticket);
                    cookie.setMaxAge(0);    //0表示立即删除
                    //规则cookie如果需要操作,必须严格定义
                    cookie.setPath("/");
                    cookie.setDomain("jt.com");
                    response.addCookie(cookie);
                }
            }
        }

        return "redirect:/";
    }


}
